﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.MonitorCommand;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers.MonitorCommandHander
{
    public class CreateMonitorCommandHander : IRequestHandler<CreateMonitorCommand, APIResult<int>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public CreateMonitorCommandHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(CreateMonitorCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var model = mapper.Map<MonitorModel>(request);

            model.Del = false;

            result.data = await db.Insertable(model).ExecuteCommandAsync();

            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "添加过程监控信息成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "添加过程监控信息失败";
            }

            return result;
        }
    }
}
